package cn.appsys.controller;

import cn.appsys.pojo.BackendUser;
import cn.appsys.service.BackendUserService;
import cn.appsys.service.InfoService;
import cn.appsys.service.VersionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/BackendUser")
public class BackendUserController {
    @Resource
    BackendUserService backendUserService;
    @Resource
    InfoService infoService;
    @Resource
    VersionService versionService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "backendlogin";
    }


    @RequestMapping("/dologin")
    public String login(@RequestParam(value = "userCode") String userCode, @RequestParam(value = "userPassword") String userPassword,
                        HttpServletRequest request) {
        BackendUser user = backendUserService.Login(userCode, userPassword);
        if (user != null) {
            request.getSession().setAttribute("userSession", user);
            return "redirect:/BackendUser/toMain";
        } else {
            request.setAttribute("error", "用户名或密码不正确");
            return "backendlogin";
        }
    }

    @RequestMapping("/toMain")
    public String toMain() {
        return "backend/main";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "chooseLogin";
    }

    @RequestMapping("/toCheck")
    public String toAdd(@RequestParam("aid") Long appid, @RequestParam("vid") Long versionId, Model model) {

        return "backend/appcheck";
    }

    @RequestMapping("/toAppList")
    public String appList() {
        return "backend/applist";
    }

    @RequestMapping("/toAppCheck")
    public String toAppCheck(@RequestParam("aid") Long aid, @RequestParam(value = "vid",required = false) Long vid, Model model) {
        model.addAttribute("appInfo", infoService.getInfoById(aid));
        model.addAttribute("appVersion", versionService.getVersionByAppId(aid));
        return "backend/appcheck";
    }

    @RequestMapping("/checkSave")
    public String checkSave(@RequestParam("status") Long status,@RequestParam("id") Long id, Model model){
        Integer result = infoService.updateStatus(id, status);
        if (result <= 0) {
            model.addAttribute("error", "审核失败");
        }
        return result > 0 ? "redirect:/BackendUser/toAppList" : "forward:/BackendUser/toAppCheck?aid="+id;
    }

}
